package com.shaoshaohuo.app.ui.fragment;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.FragmentFicationadapter;
import com.shaoshaohuo.app.adapter.Newclassificationshaopdataadapter;
import com.shaoshaohuo.app.constant.ShareKey;
import com.shaoshaohuo.app.entity.NewFactionListEntity;
import com.shaoshaohuo.app.entity.Newshaopfcationentity;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.NewHttpCofig;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.NewDetailsActivity;
import com.shaoshaohuo.app.ui.Search_Activity;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 分类
 * Created by Administrator on 2017/6/5.
 */

public class Newclassification extends NewBaseFragment implements Newclassificationshaopdataadapter.AdapterListener {
    private Handler handler = new Handler();
    private ListView shopnamelist;
    private ListView shopdate;
    private ArrayList<Newshaopfcationentity.DataBean> newshaopfcationentities;
    private FragmentFicationadapter fragmentFicationadapter;
    private NewFactionListEntity o1;
    private ArrayList<NewFactionListEntity.DataBean> factionThrees;
    private Newclassificationshaopdataadapter newclassificationshaopdataadapter;
    private TextView faction_tv_name;
    private RelativeLayout classification_rela;
    public HashMap<String, List<NewFactionListEntity.DataBean>> hashMap = new HashMap<>();
    private ImageView imageview_message;
    private SwipeRefreshLayout classification_swp;

    public static Newclassification newInstance() {
        Bundle args = new Bundle();
        Newclassification fragment = new Newclassification();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.newclassification, null);


//        RequestParam.getHeaderParams()
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initview(view);
        network();
        initdate();
        viewlisttener();


    }

    /**
     * 網絡請求
     */
    private void network() {
        ///ec_category/index
        Map<String, String> headerParams = RequestParam.getHeaderParams();
        Okhttputils.Instanse(getContext()).getnet(headerParams, getContext(), HttpConfig.BASE_HOST_URL + NewHttpCofig.APP_index, new Okhttputils.OkutListener() {

            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                final Newshaopfcationentity o1 = (Newshaopfcationentity) o;
                List<Newshaopfcationentity.DataBean> getdata = fragmentFicationadapter.getdata();

                if (o1.getData().size() > 0) {
                    o1.getData().get(0).setIsdow(true);
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        classification_swp.setRefreshing(false);
                        fragmentFicationadapter.setData(o1.getData());
                        faction_tv_name.setText(o1.getData().get(0).getName() + "(" + o1.getData().get(0).getNum() + ") ");
                        networktype(o1.getData().get(0).getCatid());
                    }
                });

            }
        }, Newshaopfcationentity.class);

    }

    public void networktype(final String catid) {
        List<NewFactionListEntity.DataBean> dataBeen = hashMap.get(catid);
        if (dataBeen != null) {
            newclassificationshaopdataadapter.setData(dataBeen);
        } else {
            final BaseActivity activity = (BaseActivity) getActivity();
            activity.startLoadingDialog();
            Map<String, String> headerParams = RequestParam.getHeaderParams();
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("catid", catid);
            stringStringHashMap.put("updateTime", "");
            Okhttputils.Instanse(getContext()).postFromBody(headerParams, HttpConfig.BASE_HOST_URL + "/ec_category/category", stringStringHashMap, new Okhttputils.OkutListener() {

                @Override
                public void error(Call call, IOException e) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            activity.dismissLoadingDialog();
                            ToastUtil.toast("未知力量带走了数据~~");
                        }
                    });
                }

                @Override
                public void error(Call call, final int code) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 356) {
                                activity.dismissLoadingDialog();
                                ArrayList<NewFactionListEntity.DataBean> dataBeen1 = new ArrayList<>();
                                newclassificationshaopdataadapter.setData(dataBeen1);
                                hashMap.put(catid, dataBeen1);
                            } else {
                                ArrayList<NewFactionListEntity.DataBean> dataBeen1 = new ArrayList<>();
                                newclassificationshaopdataadapter.setData(dataBeen1);
                                hashMap.put(catid, dataBeen1);
                                activity.dismissLoadingDialog();
                                ToastUtil.toast("未知力量带走了数据~~");

                            }

                        }
                    });
                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    final NewFactionListEntity newFactionListEntity = (NewFactionListEntity) o;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            activity.dismissLoadingDialog();
                            newclassificationshaopdataadapter.setData(newFactionListEntity.getData());
                            hashMap.put(catid, newFactionListEntity.getData());
                        }
                    });
                }
            }, NewFactionListEntity.class);

        }

    }
//    private void loaddate(NewFactionListEntity o1) {
//        List<NewFactionListEntity.Faction> list1 = o1.getData().getList();
//        if(list1.size()>0){
//            final List<NewFactionListEntity.Factiontow> list = o1.getData().getList().get(0).getSubdata();
//            for (int i = 0; i < list.size(); i++) {
//                NewFactionListEntity.Factiontow faction = list.get(i);
//                String catname = faction.getCatname();
//                Log.d("TAG", "suseff: " + catname);
//                Newshaopfcationentity newshaopfcationentity = new Newshaopfcationentity();
//                if (i == 0) {
//                    newshaopfcationentity.setIsdow(true);
//
//                } else {
//                    newshaopfcationentity.setIsdow(false);
//                }
//                newshaopfcationentities.add(newshaopfcationentity);
//            }
//            handler.post(new Runnable() {
//                @Override
//                public void run() {
//                    faction_tv_name.setText(list.get(0).getCatname() + "(" + list.get(0).getSubdata().size() + ")");
//                    fragmentFicationadapter.setData(newshaopfcationentities);
//                    newclassificationshaopdataadapter.setData(list.get(0).getSubdata());
//                }
//            });
//        }
//
//    }

    private void viewlisttener() {
        newclassificationshaopdataadapter.setAdapterListener(this);
        imageview_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), Search_Activity.class);
                startActivity(intent);
            }
        });
        shopnamelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                int a = 0;
//                FragmentFicationadapter adapter = (FragmentFicationadapter) shopnamelist.getAdapter();
//                List<Newshaopfcationentity> getdata = adapter.getdata();
//
//                for (int i = 0; i < getdata.size(); i++) {
//
//                    boolean isdow = getdata.get(i).isdow();
//                    if (isdow) {
//                        a = i;
//                        break;
//                    }
//                }
//                if (a != position) {
//
//                    List<NewFactionListEntity.FactionThree> subdata = o1.getData().getList().get(0).getSubdata().get(position).getSubdata();
//                    newclassificationshaopdataadapter.setData(subdata);
//                    faction_tv_name.setText(o1.getData().getList().get(0).getSubdata().get(position).getCatname() + "(" + subdata.size() + ")");
//                    //被点击的条目不是已经点击的条目才允许执行
//                    for (int i = 0; i < getdata.size(); i++) {
//                        getdata.get(i).setIsdow(false);
//                    }
//                    Newshaopfcationentity newshaopfcationentity = getdata.get(position);
//                    newshaopfcationentity.setIsdow(true);
//                    adapter.notifyDataSetChanged();
//                }
//
                List<Newshaopfcationentity.DataBean> getdata = fragmentFicationadapter.getdata();
                for (int i = 0; i < getdata.size(); i++) {
                    getdata.get(i).setIsdow(false);
                }
                getdata.get(position).setIsdow(true);
                fragmentFicationadapter.notifyDataSetChanged();
                faction_tv_name.setText(getdata.get(position).getName() + "(" + getdata.get(position).getNum() + ") ");
                networktype(getdata.get(position).getCatid());
            }
        });
        shopdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewFactionListEntity.DataBean newshaopfcationentity = newclassificationshaopdataadapter.getdata().get(position);
                String catid = newshaopfcationentity.getCatid();
                Intent intent = new Intent(getContext(), NewDetailsActivity.class);
                intent.putExtra(ShareKey.CATID, catid);
                intent.putExtra("imgurl", newshaopfcationentity.getImgUrl());
                getContext().startActivity(intent);
            }
        });
    }

    /**
     * 数据賦值
     */
    private void initdate() {
        newshaopfcationentities = new ArrayList<>();
        fragmentFicationadapter = new FragmentFicationadapter(getContext(), newshaopfcationentities, true);
        shopnamelist.setAdapter(fragmentFicationadapter);
        //shopdate
        factionThrees = new ArrayList<>();
        newclassificationshaopdataadapter = new Newclassificationshaopdataadapter(getActivity(), factionThrees, true);
        shopdate.setAdapter(newclassificationshaopdataadapter);
    }

    private ValueAnimator valueAnimator;
    private float[] pos = new float[2];
    private float[] tan = new float[2];

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initview(View view) {
        /*
        * topbarview的設置
        * */

        imageview_message = (ImageView) view.findViewById(R.id.imageview_message);
        imageview_message.setImageResource(R.mipmap.search);
        imageview_message.setVisibility(View.VISIBLE);
        ImageView imageview_topbar_left_backImage = (ImageView) view.findViewById(R.id.imageview_topbar_left_backImage);
        imageview_topbar_left_backImage.setVisibility(View.GONE);
          /*
        * 实际内容初始化
        * */
        shopnamelist = (ListView) view.findViewById(R.id.classification_shopname);
        shopdate = (ListView) view.findViewById(R.id.classification_shopdate);
        /**
         * 刷新
         */
        classification_swp = (SwipeRefreshLayout) view.findViewById(R.id.classification_swp);
        classification_swp.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //刷新的接口]
                hashMap.clear();
                network();

            }
        });
//textview
        faction_tv_name = (TextView) view.findViewById(R.id.faction_tv_name);

        classification_rela = (RelativeLayout) view.findViewById(R.id.classification_rela);
    }

    @Override
    public void pathmove(final PathMeasure pathMeasure, float x, float y) {
        //在这里执行加入购物车动画
        final ImageView view = new ImageView(getContext());
        view.setImageResource(R.mipmap.round_red);
        view.setLayoutParams(new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//        conten.addView(view, conten.getChildCount() - 1);
        classification_rela.addView(view);
        valueAnimator = ValueAnimator.ofFloat(0, pathMeasure.getLength());
        float length = pathMeasure.getLength();
        Log.e("TAG", "pathmove: " + length);
        long duration = (long) ((long) length > 200 ? length -= 200 : length);
        valueAnimator.setDuration(duration);
        valueAnimator.setRepeatCount(0);
        valueAnimator.setRepeatMode(ValueAnimator.RESTART);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float animatedValue = (Float) animation.getAnimatedValue();
                pathMeasure.getPosTan(animatedValue, pos, tan);
                float x = pos[0];
                float y = pos[1];
                view.setTranslationX(x);
                view.setTranslationY(y);
                Log.d("TAG", "onAnimationUpdate: " + x + "y" + y + "float" + animatedValue);
//                Newclassificationshaopdataadapter.this.view.layout((int) x, (int) y, Newclassificationshaopdataadapter.this.view.getWidth() + (int) x, Newclassificationshaopdataadapter.this.view.getHeight() + (int) y);
//                Newclassificationshaopdataadapter.this.view.setTranslationX(x);
//                Newclassificationshaopdataadapter.this.view.setTranslationY(y);

            }
        });
        valueAnimator.start();
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                classification_rela.removeView(view);


            }

            @Override
            public void onAnimationCancel(Animator animation) {
                classification_rela.removeView(view);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }
}
